<%#
 Copyright 2013-2025 the original author or authors from the JHipster project.

 This file is part of the JHipster project, see https://www.jhipster.tech/
 for more information.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      https://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-%>
<%_
let searchType = 'Search';
if (paginationPagination || paginationInfiniteScroll) {
    searchType = 'SearchWithPagination';
}
_%>
import { inject, Injectable } from '@angular/core';
import { HttpClient, HttpResponse } from '@angular/common/http';
import {
<%_ if (builtInUserManagement || anyFieldIsDateDerived) { _%>
  map,
<%_ } _%>
  Observable,
<%_ if (searchEngineAny) { _%>
  asapScheduler,
  scheduled,
<%_ } _%>
} from 'rxjs';

<%_ if (searchEngineAny) { _%>
import { catchError } from 'rxjs/operators';
<%_ } _%>

<%_ if (anyFieldIsDateDerived) { _%>
import dayjs from 'dayjs/esm';
<%_ } _%>

import { isPresent } from 'app/core/util/operators';
<%_ if (anyFieldIsLocalDate) { _%>
import { DATE_FORMAT } from 'app/config/input.constants';
<%_ } _%>
import { ApplicationConfigService } from 'app/core/config/application-config.service';
import { createRequestOption } from 'app/core/request/request-util';
<%_ if (searchEngineAny) { _%>
import { <%= searchType %> } from 'app/core/request/request.model';
<%_ } _%>
import { I<%= entityAngularName %><% if (!readOnly) { %>, New<%= entityAngularName %><% } %> } from '../<%= entityFileName %>.model';
<%_ if (!readOnly && updatableEntity) { _%>

export type PartialUpdate<%= entityAngularName %> = Partial<I<%= entityAngularName %>> & Pick<I<%= entityAngularName %>, '<%= primaryKey.name %>'>;
<%_ } _%>

<%_ const entityRestName = anyFieldIsDateDerived ? `Rest${entityAngularName}` : `I${entityAngularName}`; _%>
<%_ if (anyFieldIsDateDerived) { _%>
type RestOf<T extends I<%= entityAngularName %><% if (!readOnly) { %> | New<%= entityAngularName %><% } %>> =
  Omit<T, '<%- fields.filter(field => field.fieldTypeTemporal).map(field => field.fieldName).join("' | '") %>'> &
  {
  <%_ for (const field of fields.filter(field => field.fieldTypeTemporal)) { _%>
  <%= field.fieldName %>?: string | null;
  <%_ } _%>
  };

export type <%= entityRestName %> = RestOf<I<%= entityAngularName %>>;
  <%_ if (!readOnly) { _%>

export type New<%= entityRestName %> = RestOf<New<%= entityAngularName %>>;
  <%_ } _%>
  <%_ if (!readOnly && updatableEntity) { _%>

export type PartialUpdate<%= entityRestName %> = RestOf<PartialUpdate<%= entityAngularName %>>;
  <%_ } _%>
<%_ } _%>

export type EntityResponseType = HttpResponse<I<%= entityAngularName %>>;
export type EntityArrayResponseType = HttpResponse<I<%= entityAngularName %>[]>;

@Injectable({ providedIn: 'root' })
export class <%= entityAngularName %>Service {
    protected readonly http = inject(HttpClient);
    protected readonly applicationConfigService = inject(ApplicationConfigService);

    protected resourceUrl = this.applicationConfigService.getEndpointFor('api/<%= entityApiUrl %>'<% if ((applicationTypeGateway || applicationTypeMicroservice) && locals.microserviceName) { %>, '<%= microserviceName.toLowerCase() %>'<% } %>);
<%_ if (searchEngineAny) { _%>
    protected resourceSearchUrl = this.applicationConfigService.getEndpointFor('api/<%= entityApiUrl %>/_search'<% if ((applicationTypeGateway || applicationTypeMicroservice) && locals.microserviceName) { %>, '<%= microserviceName.toLowerCase() %>'<% } %>);
<%_ } _%>

<%_ if (!readOnly) { _%>
    create(<%= entityInstance %>: New<%= entityAngularName %>): Observable<EntityResponseType> {
    <%_ if (anyFieldIsDateDerived) { _%>
        const copy = this.convertDateFromClient(<%= entityInstance %>);
    <%_ } _%>
    <%_ if (builtInUserManagement) { _%>
        const copy = this.convertUserManagementFromClient(<%= entityInstance %>);
    <%_ } _%>
        return this.http.post<<%= entityRestName %>>(this.resourceUrl,
                <% if (anyFieldIsDateDerived || builtInUserManagement) { %> copy <% } else { %> <%= entityInstance %> <% } %>,
                { observe: 'response' })
        <% if (anyFieldIsDateDerived) { %>.pipe(map(res => this.convertResponseFromServer(res)))<% } %>
        <% if (builtInUserManagement) { %>.pipe(map(res => this.convertUserManagementResponseFromServer(res)))<% } %>;
    }
<%_ } _%>
<%_ if (!readOnly && updatableEntity) { _%>

    update(<%= entityInstance %>: I<%= entityAngularName %>): Observable<EntityResponseType> {
    <%_ if (anyFieldIsDateDerived) { _%>
        const copy = this.convertDateFromClient(<%= entityInstance %>);
    <%_ } _%>
    <%_ if (builtInUserManagement) { _%>
        const copy = this.convertUserManagementFromClient(<%= entityInstance %>);
    <%_ } _%>
        return this.http.put<<%= entityRestName %>>(`${this.resourceUrl}/${encodeURIComponent(this.get<%= entityAngularName %>Identifier(<%= entityInstance %>))}`,
                <% if (anyFieldIsDateDerived || builtInUserManagement) { %> copy <% } else { %> <%= entityInstance %> <% } %>,
                { observe: 'response' })
        <% if (anyFieldIsDateDerived) { %>.pipe(map(res => this.convertResponseFromServer(res)))<% } %>;
    }

    partialUpdate(<%= entityInstance %>: PartialUpdate<%= entityAngularName %>): Observable<EntityResponseType> {
    <%_ if (anyFieldIsDateDerived) { _%>
        const copy = this.convertDateFromClient(<%= entityInstance %>);
    <%_ } _%>
    <%_ if (builtInUserManagement) { _%>
        const copy = this.convertUserManagementFromClient(<%= entityInstance %>);
    <%_ } _%>
        return this.http.patch<<%= entityRestName %>>(`${this.resourceUrl}/${encodeURIComponent(this.get<%= entityAngularName %>Identifier(<%= entityInstance %>))}`,
                <% if (anyFieldIsDateDerived || builtInUserManagement) { %> copy <% } else { %> <%= entityInstance %> <% } %>,
                { observe: 'response' })
        <% if (anyFieldIsDateDerived) { %>.pipe(map(res => this.convertResponseFromServer(res)))<% } %>
        <% if (builtInUserManagement) { %>.pipe(map(res => this.convertUserManagementResponseFromServer(res)))<% } %>;
    }
<%_ } _%>

    find(id: <%= tsKeyType %>): Observable<EntityResponseType> {
        return this.http.get<<%= entityRestName %>>(`${this.resourceUrl}/${encodeURIComponent(id)}`, { observe: 'response' })
            <% if (anyFieldIsDateDerived) { %>.pipe(map(res => this.convertResponseFromServer(res)))<% } %>
            <% if (builtInUserManagement) { %>.pipe(map(res => this.convertUserManagementResponseFromServer(res)))<% } %>;
    }

    query(req?: any): Observable<EntityArrayResponseType> {
        const options = createRequestOption(req);
        return this.http.get<<%= entityRestName %>[]>(this.resourceUrl, { params: options, observe: 'response' })
            <% if (anyFieldIsDateDerived) { %>.pipe(map(res => this.convertResponseArrayFromServer(res)))<% } %>
            <% if (builtInUserManagement) { %>.pipe(map(res => this.convertUserManagementResponseArrayFromServer(res)))<% } %>;
    }

<%_ if (!readOnly) { _%>
    delete(id: <%= tsKeyType %>): Observable<HttpResponse<{}>> {
        return this.http.delete(`${this.resourceUrl}/${encodeURIComponent(id)}`, { observe: 'response' });
    }
<%_ } _%>

<%_ if (searchEngineAny) { _%>
    search(req: <%= searchType %>): Observable<EntityArrayResponseType> {
        const options = createRequestOption(req);
        return this.http.get<<%= entityRestName %>[]>(this.resourceSearchUrl, { params: options, observe: 'response' })
            .pipe(
              <% if (anyFieldIsDateDerived) { %>map(res => this.convertResponseArrayFromServer(res)), <% } %>
              <% if (builtInUserManagement) { %>.pipe(map(res => this.convertUserManagementResponseArrayFromServer(res)))<% } %>
              catchError(() => scheduled([new HttpResponse<I<%= entityAngularName %>[]>()], asapScheduler)),
            );
    }
<%_ } _%>

    get<%= entityAngularName %>Identifier(<%= entityInstance %>: Pick<I<%= entityAngularName %>, '<%= primaryKey.name %>'>): <%= primaryKey.tsType %> {
        return <%= entityInstance %>.<%= primaryKey.name %>;
    }

    compare<%= entityAngularName %>(o1: Pick<I<%= entityAngularName %>, '<%= primaryKey.name %>'> | null, o2: Pick<I<%= entityAngularName %>, '<%= primaryKey.name %>'> | null): boolean {
        return o1 && o2 ? this.get<%= entityAngularName %>Identifier(o1) === this.get<%= entityAngularName %>Identifier(o2) : o1 === o2;
    }

    add<%= entityAngularName %>ToCollectionIfMissing<Type extends Pick<I<%= entityAngularName %>, '<%= primaryKey.name %>'>>(<%= entityInstance %>Collection: Type[], ...<%= entityInstancePlural %>ToCheck: (Type | null | undefined)[]): Type[] {
        const <%= entityInstancePlural %>: Type[] = <%= entityInstancePlural %>ToCheck.filter(isPresent);
        if (<%= entityInstancePlural %>.length > 0) {
            const <%= entityInstance %>CollectionIdentifiers = <%= entityInstance %>Collection.map(<%= entityInstance %>Item => this.get<%= entityAngularName %>Identifier(<%= entityInstance %>Item));
            const <%= entityInstancePlural %>ToAdd = <%= entityInstancePlural %>.filter(<%= entityInstance %>Item => {
                const <%= entityInstance %>Identifier = this.get<%= entityAngularName %>Identifier(<%= entityInstance %>Item);
                if (<%= entityInstance %>CollectionIdentifiers.includes(<%= entityInstance %>Identifier)) {
                    return false;
                }
                <%= entityInstance %>CollectionIdentifiers.push(<%= entityInstance %>Identifier);
                return true;
            });
            return [...<%= entityInstancePlural %>ToAdd, ...<%= entityInstance %>Collection];
        }
        return <%= entityInstance %>Collection;
    }

<%_ if (anyFieldIsDateDerived) { _%>
    protected convertDateFromClient<T extends I<%= entityAngularName %><% if (!readOnly) { %> | New<%= entityAngularName %><% } %><% if (!readOnly && updatableEntity) { %> | PartialUpdate<%= entityAngularName %><% } %>>(<%= entityInstance %>: T): RestOf<T> {
        return {
            ...<%= entityInstance %>,
    <%_ for (const field of fields) { _%>
        <%_ if (field.fieldTypeTimed) { _%>
        <%= field.fieldName %>: <%= entityInstance %>.<%= field.fieldName %>?.toJSON() ?? null,
        <%_ } _%>
        <%_ if (field.fieldTypeLocalDate) { _%>
        <%= field.fieldName %>: <%= entityInstance %>.<%= field.fieldName %>?.format(DATE_FORMAT) ?? null,
        <%_ } _%>
    <%_ } _%>
        };
    }

    protected convertDateFromServer(rest<%= entityAngularName %>: <%= entityRestName %>): I<%= entityAngularName %> {
        return {
            ...rest<%= entityAngularName %>,
    <%_ for (const field of fields.filter(field => field.fieldTypeTemporal)) { _%>
            <%= field.fieldName %>: rest<%= entityAngularName %>.<%= field.fieldName %> ? dayjs(rest<%= entityAngularName %>.<%= field.fieldName %>) : undefined,
    <%_ } _%>
        }
    }

  protected convertResponseFromServer(res: HttpResponse<<%= entityRestName %>>): HttpResponse<I<%= entityAngularName %>> {
    return res.clone({
      body: res.body ? this.convertDateFromServer(res.body) : null,
    });
  }

  protected convertResponseArrayFromServer(res: HttpResponse<<%= entityRestName %>[]>): HttpResponse<I<%= entityAngularName %>[]> {
    return res.clone({
      body: res.body ? res.body.map(item => this.convertDateFromServer(item)) : null,
    });
  }
<%_ } _%>
<%_ if (builtInUserManagement) { _%>

  protected convertUserManagementFromClient<T extends I<%= entityAngularName %><% if (!readOnly) { %> | New<%= entityAngularName %><% } %><% if (!readOnly && updatableEntity) { %> | PartialUpdate<%= entityAngularName %><% } %>>(<%= entityInstance %>: T): any {
    return {
      ...<%= entityInstance %>,
      authorities: <%= entityInstance %>.authorities?.map(authority => authority.name),
    };
  }

  protected convertUserManagementFromServer(rest<%= entityAngularName %>: <%= entityRestName %>): I<%= entityAngularName %> {
    return {
      ...rest<%= entityAngularName %>,
      authorities: rest<%= entityAngularName %>.authorities?.map(authority => ({ name: authority as unknown as string })),
    }
  }

  protected convertUserManagementResponseFromServer(res: HttpResponse<<%= entityRestName %>>): HttpResponse<I<%= entityAngularName %>> {
    return res.clone({
      body: res.body ? this.convertUserManagementFromServer(res.body) : null,
    });
  }

  protected convertUserManagementResponseArrayFromServer(res: HttpResponse<<%= entityRestName %>[]>): HttpResponse<I<%= entityAngularName %>[]> {
    return res.clone({
      body: res.body ? res.body.map(item => this.convertUserManagementFromServer(item)) : null,
    });
  }
<%_ } _%>
}
